<?php

namespace app\model;

use Laf\Log;
use mon\orm\Model;
use mon\util\Instance;
use mon\util\Container;
use mon\orm\exception\DbException;

/**
 * 权限规则模型
 *
 * Class AuthAccess
 * @copyright 2021-03-24 mon-console
 * @version 1.0.0
 */
class AuthAccessModel extends Model
{
    use Instance;

    /**
     * 操作表
     *
     * @var string
     */
    protected $table = 'auth_access';

    /**
     * 新增自动写入字段
     *
     * @var array
     */
    protected $insert = ['create_time', 'update_time'];

    /**
     * 更新自动写入字段
     *
     * @var array
     */
    protected $update = ['update_time'];

    /**
     * 日志驱动
     *
     * @var string
     */
    protected $validate = \app\validate\Auth::class;

    /**
     * 查询信息
     *
     * @param array $where where条件
     * @param mixed $field 查询字段
     * @return mixed
     */
    public function getInfo(array $where, $field = '*')
    {
        $info = $this->where($where)->field($field)->find();
        if (!$info) {
            $this->error = '记录信息不存在';
            return false;
        }

        return $info;
    }

    /**
     * 新增用户绑定
     *
     * @param integer $gid
     * @param integer $uid
     * @return boolean
     */
    public function addBind($gid, $uid)
    {
        $this->startTrans();
        try {
            $accessModel = Container::instance()->auth->model('access');
            Log::instance()->oss(__FILE__, __LINE__, 'bind admin group', 'sql');
            $save = $accessModel->bind([
                'uid'   => $uid,
                'gid'   => $gid
            ]);
            if (!$save) {
                $this->rollback();
                $this->error = $accessModel->getError();
                return false;
            }

            // 记录操作日志
            $record = AdminLogModel::instance()->record(['action' => '管理员绑定角色组', 'content' => '管理员绑定角色组别，角色组ID：' . $gid . '，管理员ID：' . $uid]);
            if (!$record) {
                $this->rollback();
                $this->error = '记录操作日志失败';
                return false;
            }

            $this->commit();
            return true;
        } catch (DbException $e) {
            $this->rollback();
            Log::instance()->oss(__FILE__, __LINE__, 'group add bind user exception, msg => ' . $e->getMessage(), 'error');
            $this->error = '绑定角色组别用户异常';
            return false;
        }
    }

    /**
     * 绑定用户到角色组
     *
     * @param array   $option    请求参数
     * @return boolean
     */
    public function bindUsers(array $option)
    {
        $check = $this->validate()->data($option)->scope('bind_group')->check();
        if ($check !== true) {
            $this->error = $this->validate()->getError();
            return false;
        }
        // 判断组别是否存在
        $groupInfo = AuthGroupModel::instance()->where(['id' => $option['idx']])->find();
        if (!$groupInfo) {
            $this->error = '角色组别不存在';
            return false;
        }
        $accessModel = Container::instance()->auth->model('access');
        Log::instance()->oss(__FILE__, __LINE__, 'reset bind admin for group', 'sql');
        // 事务批量绑定用户
        $this->startTrans();
        try {
            // 先删除所有旧的组别用户关联
            $del = $this->where('group_id', $option['idx'])->delete();
            if (!$del && $del !== 0) {
                $this->rollback();
                $this->error = '清空角色组别旧用户绑定失败';
                return false;
            }

            // 绑定用户
            $uids = explode(',', $option['uids']);
            foreach ($uids as $k => $item) {
                if (!empty($item)) {
                    Log::instance()->oss(__FILE__, __LINE__, 'bind admin group', 'sql');
                    $save = $accessModel->bind([
                        'uid'   => $item,
                        'gid'   => $option['idx']
                    ]);
                    if (!$save) {
                        $this->rollback();
                        $this->error = $accessModel->getError();
                        return false;
                    }
                }
            }

            // 记录操作日志
            $record = AdminLogModel::instance()->record(['action' => '管理员绑定角色组', 'content' => '管理员绑定角色组别，角色组ID：' . $option['idx'] . '，管理员ID列表：' . $option['uids']]);
            if (!$record) {
                $this->rollback();
                $this->error = '记录操作日志失败';
                return false;
            }

            $this->commit();
            return true;
        } catch (DbException $e) {
            $this->rollback();
            Log::instance()->oss(__FILE__, __LINE__, 'group bind user exception, msg => ' . $e->getMessage(), 'error');
            $this->error = '绑定角色组别用户异常';
            return false;
        }
    }

    /**
     * 自动完成create_time字段
     * 
     * @param mixed $val 默认值
     * @param array  $row 列值
     * @return string
     */
    protected function setCreateTimeAttr($val)
    {
        return time();
    }

    /**
     * 自动完成update_time字段
     * 
     * @param mixed $val 默认值
     * @param array  $row 列值
     * @return string
     */
    protected function setUpdateTimeAttr($val)
    {
        return time();
    }
}
